#!/usr/bin/env python
# -*- encoding:gb2312 -*-

import os
import sys

from plugins import CheckPlugin
from config import cwd, logger, plugin_prefix
from notifier import Notifier

__author__ = 'yangxiaoyong <yxy0076@175game.com>'


class PluginManager(object):
    def __init__(self, notifier, plugin_dir=None, plugin_inti_args={}):
        self.notifier = notifier
        self.plugin_dir = plugin_dir if plugin_dir else os.path.join(cwd, 'plugins')
        self.plugins = {}
        self._load_plugins()
        self._register_plugins(**plugin_inti_args)

    def _find_plugin_files(self):
        self.plugin_files = [fn for fn in os.listdir(self.plugin_dir)
                if fn.startswith(plugin_prefix) and fn.endswith('.py')]

    def _load_plugins(self):
        '''Load plugins '''

        self._find_plugin_files()
        sys.path.append(self.plugin_dir)
        plugin_modules = [m.split('.')[0] for m in self.plugin_files]
        for module in plugin_modules:
            logger.debug('load plugin %s' % module)
            m = __import__(module, level=1)

    def _register_plugins(self, **kwargs):
        for plugin in CheckPlugin.__subclasses__():
            obj = plugin(**kwargs)
            self.plugins[obj] = obj.keywords if hasattr(obj, 'keywords') else []

    def call_method(self, method, args={}, keywords=[]):
        for plugin in self.plugins:
            logger.debug('-' * 15)
            plugin.check()
            self.notifier.notify(getattr(plugin, method)(**args))

def main():
    plugin_mgr = PluginManager(Notifier('to_print'))
    plugin_mgr.call_method('to_json')

if __name__ == "__main__":
    main()


